<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@page import="java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.File" %>
<%@ page import = "java.io.InputStream" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Employee</title>
	
	<link rel="stylesheet" type="text/css" href="css/stylev2.css" />
	<link rel="stylesheet" type="text/css" href="css/student-system.css" />
	<link rel="stylesheet" type="text/css" href="css/menubar.css" />
	<link rel="stylesheet" type="text/css" href="css/frame.css" />
	<link rel="stylesheet" type="text/css" href="css/frame.css" />
	
	<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
	
	<style>

		.silvergrad td {
		    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFF', endColorstr='#CCC');
		    background: -webkit-gradient(linear, left top, left bottom, from(#FFF), to(#CCC));
		    background: -moz-linear-gradient(top, #FFF, #CCC);
		}
		.silvergrad:hover td {
		    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#999', endColorstr='#CCC');
		    background: -webkit-gradient(linear, left top, left bottom, from(#999), to(#CCC));
		    background: -moz-linear-gradient(top, #999, #CCC);
		    
		    cursor: pointer;
		}
		
		.bluegrad td {
		    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#c9e3fd', endColorstr='#aad4ff');
		    background: -webkit-gradient(linear, left top, left bottom, from(#c9e3fd), to(#aad4ff));
		    background: -moz-linear-gradient(top, #c9e3fd, #aad4ff);
		}
		.bluegrad:hover td {
		    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#85b7eb', endColorstr='#cae1f8');
		    background: -webkit-gradient(linear, left top, left bottom, from(#85b7eb), to(#cae1f8));
		    background: -moz-linear-gradient(top, #85b7eb, #cae1f8);
		    
		    cursor: pointer;
		}
		
		.silver {
		    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFF', endColorstr='#CCC');
		    background: -webkit-gradient(linear, left top, left bottom, from(#FFF), to(#CCC));
		    background: -moz-linear-gradient(top, #FFF, #CCC);
		}
		.silver:hover {
		    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#999', endColorstr='#CCC');
		    background: -webkit-gradient(linear, left top, left bottom, from(#999), to(#CCC));
		    background: -moz-linear-gradient(top, #999, #CCC);
		    
		    cursor: pointer;
		}
		
		.blue  {
		    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#c9e3fd', endColorstr='#aad4ff');
		    background: -webkit-gradient(linear, left top, left bottom, from(#c9e3fd), to(#aad4ff));
		    background: -moz-linear-gradient(top, #c9e3fd, #aad4ff);
		}
		.blue:hover {
		    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#85b7eb', endColorstr='#cae1f8');
		    background: -webkit-gradient(linear, left top, left bottom, from(#85b7eb), to(#cae1f8));
		    background: -moz-linear-gradient(top, #85b7eb, #cae1f8);
		    
		    cursor: pointer;
		}
		a {
	      text-decoration:none;
	   }
	</style>
	
	<script type="text/javascript">
	
		$(document).ready(function(){
			
			 $("#result_div").hide();
			
		 	 $("button").click(function(){
		 		 var fullname = document.getElementById("name_in").value;
		 		 var name_temp = fullname.split(" ");
		 		 var name = "";
				 var surname = "";
				 
				 var name_is_null = 1; //1 for null
		 		 var depart_is_null = 1;
				 
				 if(name_temp.length == 2) {
					name = fullname.substr(0,fullname.indexOf(' '));
					if(/^[@#$%^&*()-_+=!,0-9]*$/.test(name) == true) { 
						
						//alert("name");///////////////////////////////////////////////
						
						alert("กรุณากรอก ชื่อและนามสกุลให้ถูกต้องค่ะ");
						return false;
					}
					surname = fullname.substr(fullname.indexOf(' ')+1).trim();
					if(/^[@#$%^&*()-_+=!,0-9]*$/.test(surname) == true) { 
						
						//alert("surname");///////////////////////////////////////////////
						
						alert("กรุณากรอก ชื่อและนามสกุลให้ถูกต้องค่ะ");
						return false;
					}
					
					name_is_null = 0;
				}
				 else if(fullname.length > 0 && name_temp != 2){
					 alert("กรุณากรอก ชื่อและนามสกุลให้ถูกต้องค่ะ");
						return false;
				 }
				 
		 		 var select = document.getElementById("department_in");
				 var department_in = select.options[select.selectedIndex].value;
				 if(department_in=="select"){
				 }
				 else{
			 			
		 			 depart_is_null = 0;
		 		 }
		 		
		//		 alert("name : "+name.length+" surname : "+surname.length);/////try//////
		//		 alert("department_in : "+department_in);/////try//////
		 		 
		 	
		 	//	 alert(name_is_null +""+ id_is_null +""+ depart_is_null +""+ year_is_null);
		 		 if(name_is_null+depart_is_null==2)
		 		{
		 			 	alert("กรุณาใส่ keyword ในการค้นหา");		 
		 			 	return false;
		    	 }
		 		
		 		// alert("name:"+name_in+" id:"+id_in+" department:"+department_in+" year:"+year_in);
		 		
		 		var option = "";
		 		option = name_is_null.toString()+depart_is_null.toString();
		 		
		 		var sql_con = ""; 
		// 		alert("option is:"+option);//////////////
		 		
		 		switch(option){
					case "00":
		 				sql_con =  sql_con+" AND N.name_th='"+name+"' AND N.surname_th='"+surname+"'"
							+" AND D.department_id="+department_in;
		 				break;
		 				
		 			case "01":
		 				sql_con =  sql_con+" AND N.name_th='"+name+"' AND N.surname_th='"+surname+"'";
		 				break;
		 				
		 			case "10":
			 				sql_con =  sql_con+" AND D.department_id="+department_in;
		 				break;
		 		}
		// 		alert("sql_con1:"+sql_con);////////////try////////////		
	 			/* AJAX */	
			  	var xmlhttp;
				
				if(window.XMLHttpRequest) {
					// code for IE7+, Firefox, Chrome, Opera, Safari
					xmlhttp = new XMLHttpRequest();
				}
				else {
					// code for IE6, IE5
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				}
				
				xmlhttp.onreadystatechange = function() {
					if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {	
					//	alert("I'm Back");//////////////////
						
						if($('#result_div').find('div').length > 0) {					
							$('#result_div').find('div').remove();
						}
						
						var jsonObj = JSON.parse(xmlhttp.responseText);
						
						//alert("I'm Back");
						if(jsonObj.length == 0) {
						//	massage();
							alert("ไม่พบข้อมูล");
						}
						else{
						//	alert("That work !!!");
							
							
							head = '<div class="CSSTableGenerator">'
									+ '<table  width="950" border="1" align="center" id="table_student">'
									+ '<tr>'
					              	+ '<td width="100"><center><strong>ชื่อ</strong></center></td>'
					              	+ '<td width="130"><center><strong>นามสกุล</strong></center></td>'
					              	+ '<td width="80"><center><strong>ภาควิชา</strong></center></td>'
					              	+ '<td width="40"><center><strong>ตำแหน่ง</strong></center></td>'
					              	+ '<td width="40"><center><strong>แก้ไข</strong></center></td>'
					              	+ '<td width="40"><center><strong>กรณีเปลี่ยนชื่อ</strong></center></td>'
					              	+ '<td width="40"><center><strong></strong></center></td>'
					              	+ '</tr>';
									
							$('#result_div').append(head);
						
							for(i in jsonObj) {
								if(i%2 == 0) { 
									class_name = 'silvergrad';
									
									class_name2 = 'blue';
								}
								else {
									class_name = 'bluegrad';
									
									class_name2 = 'silver';
								}
								
								text = '<tr class="'+class_name+'">'
										+ '<td width="80" onclick="show_employee_detail(\''+jsonObj[i].index+'\')"><center>'+jsonObj[i].nameTH+'</center></td>'
										+ '<td width="80" onclick="show_employee_detail(\''+jsonObj[i].index+'\')"><center>'+jsonObj[i].surnameTH+'</center></td>'
										+ '<td width="80" onclick="show_employee_detail(\''+jsonObj[i].index+'\')"><center>'+jsonObj[i].department+'</center></td>';										
								
								if(jsonObj[i].position == "") {
									text = text	+ '<td width="80" onclick="show_employee_detail(\''+jsonObj[i].index+'\')"><center>-</center></td>';
								}
								else {
									text = text + '<td width="80" onclick="show_employee_detail(\''+jsonObj[i].index+'\')"><center>'+jsonObj[i].position+'</center></td>'
								}	
								
								var name_delete = jsonObj[i].nameTH+" "+jsonObj[i].surnameTH;
										
								text = text	 + '<td width="80" class="'+class_name2+'" onclick="to_employee_edit_personal(\''+jsonObj[i].index+'\')"><center>ข้อมูลส่วนตัว</center></td>'
 								+ '<td width="80" class="'+class_name2+'" onclick="to_employee_edit_name(\''+jsonObj[i].index+'\')"><center>ชื่อ-นามสกุล</center></td>'
 								+ '<td><center><span title="ลบข้อมูล"><img src="image/delete_icon.png" height="30px" width="30px" onclick="deleteButton(\''+jsonObj[i].index+'\', \''+name_delete+'\')" /></span></center></td>'
 								+ '</tr>';
										
								$('#table_student').append(text);
							}
							
							$('#result_div').append('</table></div>');
						}				
					
					}// end if check state
				}// end function
				
				//xmlhttp.open("POST", "student_search_background.jsp?user_input_search=" + user_search_input+"&option="+option_value, true);
		//		alert("sql_con:"+sql_con);////////////try////////////
				xmlhttp.open("POST", "admin_employee_search.jsp?sql_con="+sql_con, true);				
				xmlhttp.send();
			  
			  $("#result_div").show();
		  });
		 	 
		});
		
		function add_employee() {
			document.location.href = "admin_employee_add.jsp";
		}
		
		function search_name(name) {	
			if($('#namelist').find('option').length > 0) {
				
				$('#namelist').find('option').remove();
			}
			if(name != "") {
				/* AJAX */
				var xmlhttp;
				
				if(window.XMLHttpRequest) {
					// code for IE7+, Firefox, Chrome, Opera, Safari
					xmlhttp = new XMLHttpRequest();
				}
				else {
					// code for IE6, IE5
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				}
				
				xmlhttp.onreadystatechange = function() {
					if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {						
						var jsonObj = JSON.parse(xmlhttp.responseText);
						
						if(jsonObj.length == 0) {
							// no data
						}
						else{
							for(i in jsonObj) {
								var text = jsonObj[i].nameTH+" "+jsonObj[i].surnameTH;
								var option = '<option value="'+text+'" >';
								
								$('#namelist').append(option);
							}
						}
					}
				}
				
				xmlhttp.open("POST", "search_name_employee.jsp?name="+name, true);
				xmlhttp.send();
			}			
		}
		
		function show_employee_detail(id){

		 	var form = document.createElement("form");
		    form.setAttribute("method", "post");
		    form.setAttribute("action", "admin_employee_detail.jsp");
		    var hiddenField = document.createElement("input");
		    hiddenField.setAttribute("type", "hidden");
	        hiddenField.setAttribute("name", "index");
	        hiddenField.setAttribute("id","index");
	        hiddenField.setAttribute("value", id);
	        form.appendChild(hiddenField);
	        
	        document.body.appendChild(form);
	        form.submit();
		}

		function to_employee_edit_personal(id){
			
			  var form = document.createElement("form");
		  	      form.setAttribute("method", "post");
		    	  form.setAttribute("action", "admin_employee_edit_personal.jsp");
		 	  var hiddenField = document.createElement("input");
		          hiddenField.setAttribute("type", "hidden");
		          hiddenField.setAttribute("name", "index");
		          hiddenField.setAttribute("id","index");
		          hiddenField.setAttribute("value", id);
		       form.appendChild(hiddenField);
		  
		  document.body.appendChild(form);
		  form.submit();
			
		}		

		function to_employee_edit_name(id){
			  var form = document.createElement("form");
			      form.setAttribute("method", "post");
			      form.setAttribute("action", "admin_employee_edit_name.jsp");
			      
			  var hiddenField = document.createElement("input");
			      hiddenField.setAttribute("type", "hidden");
		          hiddenField.setAttribute("name", "index");
		          hiddenField.setAttribute("id","index");
		          hiddenField.setAttribute("value", id);
		          
		      var hiddenField2 = document.createElement("input");
			      hiddenField2.setAttribute("type", "hidden");
		          hiddenField2.setAttribute("name", "checker");
		          hiddenField2.setAttribute("id","checker");
		          hiddenField2.setAttribute("value", "NONE");
		          
		      form.appendChild(hiddenField);
		      form.appendChild(hiddenField2);
		      
		      document.body.appendChild(form);
		      form.submit();
			
			
		}
		
		function deleteButton(index, name) {
			
			if (confirm("คุณต้องการจะลบข้อมูล " + name) == true) {
				/* AJAX */
				var xmlhttp;
				
				if(window.XMLHttpRequest) {
					// code for IE7+, Firefox, Chrome, Opera, Safari
					xmlhttp = new XMLHttpRequest();
				}
				else {
					// code for IE6, IE5
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				}
				
				xmlhttp.onreadystatechange = function() {
					if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
						var result = xmlhttp.responseText.trim();

						if(result == "success") {
							window.location.reload();
							alert("สำเร็จ");
						}
						else if(result == "fail") {
							alert("ไม่สามารถลบข้อมูลได้ค่ะ");
						}
						else {
							alert("ไม่สามารถลบข้อมูลได้ค่ะ");
						}
					}
				}
				
				xmlhttp.open("POST", "admin_employee_delete.jsp?index="+index, true);
				xmlhttp.send();
		    } else { }
		}
		
	</script>
</head>
<body>

<%
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
			
	// check session
		if (htp_session == null || htp_session.getAttribute("sUser") == null) {
		    // Forward the control to login.jsp if authentication fails or session expires
		    request.getRequestDispatcher("/login.jsp").forward(request,
		        response);
		}
		if(!"admin".equals(htp_session.getAttribute("sUser"))){%>
			<script>alert("This user dont have PERMISSION to access this zone.");</script>
			<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=system_select.jsp"> 	
	<%}
	
	//set Database Connection
	String hostProps = "";
	String usernameProps  = "";
	String passwordProps  = "";
	String databaseProps = "";
	
	try {
		//get current path
		ServletContext servletContext = request.getSession().getServletContext();
		
		InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
		Properties props = new Properties();
		
		props.load(input);

		hostProps  = props.getProperty("host");
		usernameProps  = props.getProperty("username");
		passwordProps  = props.getProperty("password");
		databaseProps = props.getProperty("database");
	} catch (Exception e) { 
		out.println(e);  
	}
	
	// connect database
	Connection connect = null;		
	try {
		Class.forName("com.mysql.jdbc.Driver");
	
		connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
				"?user=" + usernameProps  + "&password=" + passwordProps );
	
		if(connect != null){
			System.out.println("Database Connect Sucesses.");
		} else {
			System.out.println("Database Connect Failed.");	
		}

	} catch (Exception e) {
		out.println(e.getMessage());
		e.printStackTrace();
	}
	
	
	/* find department in database */
	List<Department> department = new ArrayList<Department>();
	
	try {		
		ResultSet rs_department;

	    rs_department = connect.createStatement().executeQuery("SELECT department_id, department_name_th " 
				+ " FROM department " + " ORDER BY department_id");

		
		while(rs_department.next()) {
			Department dep = new Department();
			
			dep.setDepartmentNameTH(rs_department.getString("department_name_th"));
			dep.setDepartmentId(Integer.parseInt(rs_department.getString("department_id")));
			
			department.add(dep);
		}
		
	} catch (SQLException e) {
		e.printStackTrace();
	}

	connect.close();
%>

    <div id="page-wrap">
		<div id="inside">
			<table border="0">
				<tr style="font-size:24px">
					<td width="600" height="100" style= "background-color: #273b80;border: 0px ;padding: 0px; 0px;" >
						<div id="header_banner-2"></div>
					</td>
					
					<td width="680" height="100" style= "background-color: #273b80;border: 0px;padding: 0px; 0px;" >
						<p align="right"><label><font size="4" color="#ffffff">username : <%=strUser%>&nbsp;&nbsp;</font></label></p>
						<a href="logout.jsp"><p align="right"><label style="cursor: pointer;"><font size="3" color="#ffffff">log out &nbsp;</font></label></p></a>
					</td>
				</tr>
			</table>
			
			<ul id="drop-nav">
		        <li><a href="admin_home.jsp">หน้าแรก</a> </li>
		        
		        <li>
		            <a>องค์กร &nbsp; &#9662;</a>
		            <ul>
		                <li><a href="admin_department.jsp">ภาควิชา</a></li>
		                <li><a href="admin_workgroup.jsp">หน่วยงาน</a></li>
		            </ul>
		        </li>
		        <li><a href="admin_role.jsp">หน้าที่</a></li>
		        <li><a href="admin_account.jsp">บัญชีผู้ใช้</a></li>
		        <li>
		        	<span><a>บุคคล &nbsp; &#9662;</a></span>
		        	<ul>
		                <li><a href="admin_lecturer.jsp">อาจารย์</a></li>
		                <li><a href="admin_employee.jsp">บุคลากร</a></li>
		            </ul>
		        </li>
		        <li><a href="admin_entrance.jsp">ระบบเข้าศึกษา</a></li>
		        <li><a href="admin_status.jsp">สถานะของนักศึกษา</a></li>
		        <li>
		        	<a href="">ตำแหน่ง &nbsp; &#9662;</a>
		        	<ul>
		                <li><a href="admin_educate_position.jsp">ตำแหน่งทางวิชาการ</a></li>
		                <li><a href="admin_management_position.jsp">ตำแหน่งบริหาร</a></li>
		            </ul>
		        </li>
		    </ul>
				
				<div id="main-content-ac">
						<br/><br/><br/><br/>
						
						<table style="border: 0px">
							<tr style="border: 0px">
								<td style="border: 0px">
									<div class="imageFrame">บุคลากร</div>
								</td>
								<td style="border: 0px">
									<div style="margin-top: 30px; margin-left: 20px; cursor: pointer;">
										<span title="เพิ่มข้อมูล">
											<img src="image/add_icon.png" width="40px" height="40px" onclick="add_employee()">	
										</span>
									</div>
								</td>
							</tr>
						</table>
						
						<br/><br/><br/><br/>
						
						<center>
		
										<div style="font-size:15px;">
					  	<center>
							 <font size="5"> ชื่อ <input type="text" name="name_in" id="name_in" style="font-size:15px;" value="" list="namelist" autocomplete="off" onkeyup="search_name(this.value)">
							  <datalist id="namelist">
							  </datalist>
							  
							  &nbsp;&nbsp;
							  
							  ภาควิชา <select name="department_in" id="department_in" style="font-size:15px;">
							  		
							  		<option value="select">Select</option>
							  		
				<%
									for(Department dept : department) {
										if(dept.getDepartmentId() == 0) {}
										else {
				%>
										<option value="<%=dept.getDepartmentId()%>" id="<%=dept.getDepartmentId()%>"><%=dept.getDepartmentNameTH()%></option>	
				<%				
										}
									}
				%>

									</select>
								</font>
							 &nbsp;&nbsp;&nbsp;&nbsp;
							 <button style="height: 25px; width: 80px; font-size: medium; ">ค้นหา</button>
							 <br><br>							 
					</center>
				  	 </div>
				  	
			
				  	<center><div id="result_div">
				  	 </div></center>	
						
						<br><br><br><br>
				
			<div style="clear: both;"></div>
				
			<div id="footer"></div>
			
		</div>		
			<div style="clear: both;"></div>		
   </div>

</body>
</html>